package com.shiguiwu.springmybatis.spring.property;

import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.MapPropertySource;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: 属性取值@value
 * @author: stone
 * @date: Created by 2021/4/3 19:38
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.spring.property
 */
public class DbPropertyTests {

    public static void main(String[] args) throws SQLException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        //下面是关键的代码
        //1,从db中读取配置
        List<Entity> config = DbUtil.use().findAll("xxl_config");
        Map<String, Object> collect = config.parallelStream()
                .collect(Collectors.toMap(k -> k.getStr("key"), v -> v.getStr("value")));
        //2,将其丢在MapPropertySource(MapPropertySource 是spring提供的一个类，是PropertySource 的一个子类)

        //将mailPropertySource丢在Environment中的PropertySource列表的第一个中，让优先级最高
        MapPropertySource mapPropertySource = new MapPropertySource("mail", collect);
        //将mailPropertySource丢在Environment中的PropertySource列表的第一个中，让优先级最高
         context.getEnvironment().getPropertySources().addFirst(mapPropertySource);
       /*上面这段是关键 end*/


        context.register(MailConfig.class);
        context.refresh();

        MailConfig bean = context.getBean(MailConfig.class);

        System.out.println(bean);

    }
}
